import {
  Avatar,
  Button,
  FilledInput,
  FormControl,
  Grid,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { useTheme } from "@mui/material/styles";
import OutlinedInput from "@mui/material/OutlinedInput";
import React from "react";
import { Box } from "@mui/system";
import { useEffect } from "react";
import { useState } from "react";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { useContext } from "react";
import { TitleContext } from "../../../router";
import Loading from "../../../components/loading";
import { useSnackbar } from "notistack";
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
import { useNavigate } from "react-router-dom";
import { UserContext, UserIdContext } from "../../../App";
import LoadingButton from "../../../components/LoadingButton";
import Autocomplete from "@mui/material/Autocomplete";
import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import Checkbox from "@mui/material/Checkbox";
import FormControlLabel from "@mui/material/FormControlLabel";
import Stack from "@mui/material/Stack";
import IconButton from "@mui/material/IconButton";
import Application from "./Application";
import "./CourseApplication.css";
import { useMutation } from "@tanstack/react-query";
import { GET_COURSEAPPLICATION_URL } from "../../../constants/url";
import { PUT_COURSEAPPLICATION_URL } from "../../../constants/url";
import { PUT_COURSEAPPLICATIONTIME_URL } from "../../../constants/url";
import { GETCOURSE_URL, GETCOURSETIME_URL } from "../../../constants/url";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import Dataform from "../../../components/Dataform";
import Radio from "@mui/material/Radio";
import { postQueryFn } from "../../../query/postQueryFn";
import RadioGroup from "@mui/material/RadioGroup";
import FormLabel from "@mui/material/FormLabel";
import { UserProContext } from "../../../App";

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250,
    },
  },
};

function getStyles(name, personName, theme) {
  return {
    fontWeight:
      personName.indexOf(name) === -1
        ? theme.typography.fontWeightRegular
        : theme.typography.fontWeightMedium,
  };
}

//  function MultipleSelect() {
//   const theme = useTheme();
//   const [personName, setPersonName] = React.useState([]);

//   const handleChange = (event) => {
//     const {
//       target: { value },
//     } = event;
//     setPersonName(
//       // On autofill we get a stringified value.
//       typeof value === 'string' ? value.split(',') : value,
//     );
//   };

//   return (
//     <div>
//       <FormControl sx={{ width: 300 ,mt: "1px",marginLeft: 5}}>
//         <InputLabel id="demo-multiple-name-label">times</InputLabel>
//         <Select
//           labelId="demo-multiple-name-label"
//           id="demo-multiple-name"
//           multiple
//           value={personName}
//           onChange={handleChange}
//           input={<OutlinedInput label="times" />}
//           MenuProps={MenuProps}
//           size="small"
//         >
//           {names.map((name) => (
//             <MenuItem
//               key={name}
//               value={name}
//               style={getStyles(name, personName, theme)}
//             >
//               {name}
//             </MenuItem>
//           ))}
//         </Select>
//       </FormControl>
//     </div>
//   );
// }

function ControlledRadioButtonsGroup(props) {
  const [value, setValue] = React.useState("单双都上课");

  const handleChange = (event) => {
    setValue(event.target.value);
    if (event.target.value == "单双都上课") {
      props.setWtype(1);
    } else if (event.target.value == "只上单周") {
      props.setWtype(2);
    } else if (event.target.value == "只上双周") {
      props.setWtype(3);
    }
  };

  return (
    <FormControl sx={{}}>
      <RadioGroup
        aria-labelledby="demo-controlled-radio-buttons-group"
        name="controlled-radio-buttons-group"
        value={value}
        onChange={handleChange}
        sx={{ display: "flex", flexDirection: "row" }}
      >
        <FormControlLabel
          value="单双都上课"
          control={<Radio />}
          label="单双都上课"
        />
        <FormControlLabel
          value="只上单周"
          control={<Radio />}
          label="只上单周"
        />
        <FormControlLabel
          value="只上双周"
          control={<Radio />}
          label="只上双周"
        />
      </RadioGroup>
    </FormControl>
  );
}

const MyTitle = ({ value }) => {
  return (
    <Typography variant="h6" sx={{ marginTop: 2, marginBottom: 1 }}>
      {value}
    </Typography>
  );
};

export default function CourseApplication() {
  const nowTitle = useContext(TitleContext);
  useEffect(() => {
    nowTitle.setnowTitle(4);
  }, []);
  const orders = [
    { label: "第一节", id: 1 },
    { label: "第二节", id: 2 },
    { label: "第三节", id: 3 },
    { label: "第四节", id: 4 },
    { label: "第五节", id: 5 },
  ];
  const weeks = [
    { label: "第一周", id: 1 },
    { label: "第二周", id: 2 },
    { label: "第三周", id: 3 },
    { label: "第四周", id: 4 },
    { label: "第五周", id: 5 },
    { label: "第六周", id: 6 },
    { label: "第七周", id: 7 },
    { label: "第八周", id: 8 },
    { label: "第九周", id: 9 },
    { label: "第十周", id: 10 },
    { label: "第十一周", id: 11 },
    { label: "第十二周", id: 12 },
    { label: "第十三周", id: 13 },
    { label: "第十四周", id: 14 },
    { label: "第十五周", id: 15 },
    { label: "第十六周", id: 16 },
    { label: "第十七周", id: 17 },
  ];
  const [proIsFetching, setProIsFetching] = useState(false);
  const [proisSuccess, setProisSuccess] = useState(true);
  const [infoSuccess, setisSuccess] = useState(false);
  const types = [
    { id: 1, name: "必修" },
    { id: 2, name: "限选" },
    { id: 3, name: "选修" },
  ];
  const plans = [
    { id: 1, name: "计算机引论" },
    { id: 2, name: "数据结构" },
    { id: 3, name: "计算机网络" },
    { id: 4, name: "算法导论" },
    { id: 5, name: "操作系统" },
    { id: 6, name: "编译原理" },
    { id: 7, name: "软件工程" },
    { id: 8, name: "计算机组织与结构" },
  ];
  const courseInfo = {
    capacity: 0,
    college: "",
    courseId: "",
    credit: 0,
    end: "",
    id: 0,
    isLock: true,
    location: "",
    name: "",
    pid: 0,
    start: "",
    teacher: "",
    tid: 0,
    type: "",
  };
  const [capacity, setCapacity] = useState(); //容量
  const [courseId, setCourseId] = useState(); //课程号
  const [course, setCourse] = useState(); //课程号
  const [name, setName] = useState(); //课程名称
  const [teacher, setTeacher] = useState(); //任课教师
  const [college, setCollege] = useState(); //开设学院
  const [credit, setCredit] = useState(); //学分
  const [location, setLocation] = useState();
  const [type, setType] = useState(); //课程类型
  const [pid, setPid] = useState();
  const [week, setWeek] = useState(); //课程周数
  const [wstart, setWstart] = useState();
  const [wend, setWend] = useState();
  const [wtype, setWtype] = useState(1);
  const [weekday, setWeekday] = useState([0]); //课程日期
  // let weekday=[0,];
  const [order, setOrder] = useState([0]); //课程节数
  // let order=[0,];
  const [nums, setNums] = useState([]);

  const weekdays = [
    { label: "星期一", id: 1 },
    { label: "星期二", id: 2 },
    { label: "星期三", id: 3 },
    { label: "星期四", id: 4 },
    { label: "星期五", id: 5 },
    { label: "星期六", id: 6 },
    { label: "星期日", id: 7 },
  ];

  const handleAdd = () => {
    let weekdayF = weekday;
    let orderF = order;
    let temp = nums;
    if (temp.length <= 5) {
      temp.push(1);
      weekdayF.push(0);
      orderF.push(0);
    }
    setNums([...temp]);
    setWeekday([...weekdayF]);
  };
  const handleDelete = () => {
    let weekdayF = weekday;
    let orderF = order;
    let temp = nums;
    if (temp.length != 0) {
      temp.pop();
      weekday.pop();
      order.pop();
    }
    setNums([...temp]);
    setNums([...temp]);
    setWeekday([...weekdayF]);
  };

  //获取课程的申请信息
  const {
    data,
    isLoading: getLoading,
    mutate: getMutate,
    isSuccess: getSuccess,
  } = useMutation(["getCourse"], mutateQueryFn);

  useEffect(() => {
    getMutate({
      url: GET_COURSEAPPLICATION_URL,
      method: "get",
      useToken: true,
    });
  }, []);
  // useEffect(() => {
  //   getMutate1({ url: GETCOURSE_URL, method: "get", useToken: true });
  // },[])
  const [rows, setRows] = useState([]);
  useEffect(() => {
    if (getSuccess) {
      setRows(
        data.data.data.map((val, key) =>
          val.status !== undefined
            ? {
                id: key + 1,
                courseId: val.courseId,
                name: val.name,
                credit: val.credit,
                capacity: val.capacity,
                location: val.location,
                status: val.status,
              }
            : {}
        )
      );
    } else {
    }
  }, [data]);

  //获取教师名字
  const userproContext = useContext(UserProContext);
  useEffect(() => {}, []);

  //课程申请
  // "capacity": 20,
  // "college": "学院",
  // "courseId": "c00",
  // "credit": 3.5,
  // "end": "2022-12-04T19:12:25.772Z",
  // "isLock": false,
  // "id": null,
  // "name": "啧",
  // "start": "2022-11-29T08:11:45.288Z",
  // "teacher": "张三",
  // "tid": 1,
  // "type": "必修",
  // "pid": 1

  //获取所有课程 --查询id
  const {
    data: courses,
    isLoading: getLoading1,
    mutate: getMutate1,
    isSuccess: getSuccess1,
  } = useMutation(["getCourse"], mutateQueryFn);
  //上传课程申请
  const {
    isLoading: updLoading,
    isSuccess: updSuccess,
    data: upddata,
    isError: updError,
    mutate: updMutate,
  } = useMutation(["updCourseApplication"], mutateQueryFn);
  //上传课程时间
  const {
    isLoading: updLoadingT,
    isSuccess: updSuccessT,
    data: upddataT,
    isError: updErrorT,
    mutate: updMutateT,
  } = useMutation(["updCourseApplicationTime"], postQueryFn);
  const { enqueueSnackbar } = useSnackbar();
  const handleUpd = () => {
    if (!courseId) {
      enqueueSnackbar("课程号不能为空", { variant: "warning" });
      return;
    }
    if (!name) {
      enqueueSnackbar("请填写课程名称", { variant: "warning" });
      return;
    }
    if (!capacity) {
      enqueueSnackbar("请填写课程容量", { variant: "warning" });
      return;
    }
    if (!college) {
      enqueueSnackbar("请填写开课学院", { variant: "warning" });
      return;
    }
    if (!type) {
      enqueueSnackbar("请填写课程类型", { variant: "warning" });
      return;
    }
    if (!credit) {
      enqueueSnackbar("请填写课程学分", { variant: "warning" });
      return;
    }
    if (!location) {
      enqueueSnackbar("请填写上课地点", { variant: "warning" });
      return;
    }
    if (!pid) {
      enqueueSnackbar("请选择培养计划", { variant: "warning" });
      return;
    }
    if (!wstart || !wend) {
      enqueueSnackbar("请填写开课时间1", { variant: "warning" });
      return;
    }
    if (wstart > wend) {
      enqueueSnackbar("课程开始时间不能提前于结束时间", { variant: "warning" });
      return;
    }
    if (weekday[0] == 0) {
      enqueueSnackbar("请填写开课时间2", { variant: "warning" });
      return;
    }
    if (order[0] == 0) {
      enqueueSnackbar("请填写开课时间3", { variant: "warning" });
      return;
    }

    // setWeek(...[weekF]);
    //
    // 上传课程信息
    updMutate({
      url: PUT_COURSEAPPLICATION_URL,
      method: "put",
      data: {
        courseId: courseId,
        name: name,
        location: location,
        teacher: userproContext.userPro?.name,
        credit: credit,
        college: college,
        type: type,
        capacity: capacity,
        pid: pid,
      },
      useToken: true,
    });
  };

  const [updbutSuccess, setUpdSuccess] = useState(false);
  useEffect(() => {
    if (updSuccess) {
      if (upddata.data.code != 0) {
        enqueueSnackbar(upddata.data.data, { variant: "error" });
        return;
      }
      getMutate1({ url: GETCOURSE_URL, method: "get", useToken: true }); //获取课程号用于上传课程时间
    }
  }, [updSuccess]);
  useEffect(() => {
    if (getSuccess1) {
      // handleWeek(); //处理上课周数
      const weekF = [];
      if (wtype == 1) {
        for (let i = wstart; i <= wend; i++) {
          weekF.push(i);
        }
      } else if (wtype == 2) {
        for (let i = wstart; i <= wend; i++) {
          if (i % 2 != 0) {
            weekF.push(i);
          }
        }
      } else if (wtype == 3) {
        for (let i = wstart; i <= wend; i++) {
          if (i % 2 == 0) {
            weekF.push(i);
          }
        }
      }
      let courseF;
      courses.data.data.map((val, key) =>
        val.courseId == courseId ? (courseF = val.id) : undefined
      );
      //上传课程时间
      updMutateT({
        Key: [
          PUT_COURSEAPPLICATIONTIME_URL,
          {
            params: {
              course: courseF,
            },
            useToken: true,
          },
        ],
        method: "put",
        params: {
          weeks: weekF,
          weekday: weekday,
          order: order,
        },
      });
    } else {
    }
  }, [getSuccess1]);
  useEffect(() => {
    if (updSuccessT) {
      if (upddataT.data.code != 0) {
        enqueueSnackbar(upddataT.data.data, { variant: "error" });
      } else if (upddataT.data.code == 0) {
        enqueueSnackbar("提交成功", { variant: "success" });
        getMutate({
          url: GET_COURSEAPPLICATION_URL,
          method: "get",
          useToken: true,
        });
        setUpdSuccess(true);
        setTimeout(() => {
          setUpdSuccess(false);
        }, 1500);
      }
    }
  }, [updSuccessT]);

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      {proIsFetching && (
        <Box
          sx={{
            width: "100%",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            minHeight: 600,
          }}
        >
          <Loading />
        </Box>
      )}
      {/*display: "flex", float: "left", */}
      {proisSuccess && !proIsFetching && (
        <Grid container spacing={2}>
          <Grid item xs={12} md={5}>
            <Paper
              elevation={2}
              sx={{ display: "flex", float: "left", width: "100%" }}
            >
              <Box
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  marginLeft: 2,
                  marginTop: 3,
                }}
              >
                <Box>
                  <Typography
                    variant="h5"
                    sx={{ marginBottom: 0, marginRight: 1, width: 100 }}
                  >
                    课程申请
                  </Typography>
                </Box>
                <Box sx={{ marginLeft: 2, marginTop: 0 }}>
                  <MyTitle value="课程号"></MyTitle>
                  <TextField
                    label="courseId"
                    size="small"
                    sx={{ width: 130 }}
                    onChange={(e) => {
                      setCourseId(e.target.value);
                    }}
                    value={courseId}
                  />
                  <MyTitle value="课程名称"></MyTitle>
                  <TextField
                    label="name"
                    size="small"
                    sx={{ width: 170 }}
                    value={name}
                    onChange={(e) => {
                      setName(e.target.value);
                    }}
                  />

                  <Typography
                    variant="h6"
                    sx={{
                      marginTop: 2,
                      marginBottom: 1,
                      marginRight: 1,
                      width: 150,
                    }}
                  >
                    开课周数
                  </Typography>
                  <Box sx={{ display: "flex", flexDirection: "row", mt: 0 }}>
                    <Autocomplete
                      id="combo-box-demo"
                      sx={{ width: 180, marginLeft: 0 }}
                      size="small"
                      options={weeks}
                      onChange={(e, newValue) => {
                        // setNewItem({ ...newItem, date: newValue });

                        setWstart(newValue.id);
                      }}
                      renderInput={(params) => (
                        <TextField {...params} label="start" />
                      )}
                    />
                    <span
                      style={{
                        marginLeft: "10px",
                        marginTop: "17px",
                        marginRight: "10px",
                      }}
                    >
                      至
                    </span>
                    <Autocomplete
                      disablePortal
                      id="combo-box-demo"
                      options={weeks}
                      sx={{ width: 180 }}
                      size="small"
                      onChange={(e, newValue) => {
                        // setNewItem({ ...newItem, date: newValue });
                        setWend(newValue.id);
                      }}
                      renderInput={(params) => (
                        <TextField {...params} label="end" />
                      )}
                    />
                  </Box>
                  <ControlledRadioButtonsGroup
                    setWtype={(e) => {
                      setWtype(e);
                    }}
                  />

                  <Typography
                    variant="h6"
                    sx={{
                      marginTop: 2,
                      marginBottom: -2,
                      marginRight: 1,
                      width: 150,
                    }}
                  >
                    每周课程
                  </Typography>
                  {/* 具体开课日期 第一个 */}
                  <Box
                    sx={{
                      mt: 3,
                      display: "flex",
                      flexDirection: "column",
                      float: "left",
                      marginLeft: 0,
                      marginBottom: 2,
                    }}
                  >
                    <Box sx={{ display: "flex", flexDirection: "row" }}>
                      <Autocomplete
                        disablePortal
                        id="combo-box-demo"
                        options={weekdays}
                        sx={{ width: 150 }}
                        size="small"
                        onChange={(e, newValue) => {
                          // setNewItem({ ...newItem, date: newValue });
                          let weekdayF = weekday;
                          weekdayF[0] = newValue.id;
                          setWeekday([...weekdayF]);
                        }}
                        renderInput={(params) => (
                          <TextField {...params} label="weekday" />
                        )}
                      />
                      <Box sx={{ marginLeft: 3 }}>
                        <Autocomplete
                          disablePortal
                          id="combo-box-demo"
                          options={orders}
                          sx={{ width: 150 }}
                          size="small"
                          onChange={(e, newValue) => {
                            // setNewItem({ ...newItem, date: newValue });
                            let orderF = order;
                            orderF[0] = newValue.id;
                            setOrder([...orderF]);
                          }}
                          renderInput={(params) => (
                            <TextField {...params} label="order" />
                          )}
                        />
                      </Box>
                      {/* <MultipleSelect/> */}
                      {/* 按钮 + - */}
                      <Stack
                        direction="row"
                        alignItems="center"
                        spacing={0}
                        marginTop={"-3px"}
                      >
                        <IconButton
                          aria-label="add"
                          size="large"
                          color="primary"
                          onClick={handleAdd}
                          sx={{ marginLeft: 0 }}
                        >
                          <AddCircleOutlineIcon />
                        </IconButton>
                        <IconButton
                          aria-label="delete"
                          size="large"
                          color="primary"
                          onClick={handleDelete}
                          sx={{ marginLeft: -2 }}
                        >
                          <RemoveCircleOutlineIcon />
                        </IconButton>
                      </Stack>
                    </Box>
                    {/* 根据点击渲染其余的 */}
                    {nums.map((num, index) => {
                      return (
                        <Box
                          key={index}
                          sx={{ display: "flex", flexDirection: "row", mt: 1 }}
                        >
                          <Autocomplete
                            disablePortal
                            id="combo-box-demo"
                            options={weekdays}
                            sx={{ width: 150 }}
                            size="small"
                            onChange={(e, newValue) => {
                              // setNewItem({ ...newItem, date: newValue });
                              let weekdayF = weekday;
                              weekdayF[index + 1] = newValue.id;
                              setWeekday([...weekdayF]);
                            }}
                            renderInput={(params) => (
                              <TextField {...params} label="weekday" />
                            )}
                          />
                          <Box sx={{ marginLeft: 3 }}>
                            <Autocomplete
                              disablePortal
                              id="combo-box-demo"
                              options={orders}
                              sx={{ width: 150 }}
                              size="small"
                              onChange={(e, newValue) => {
                                // setNewItem({ ...newItem, date: newValue });
                                let orderF = order;
                                orderF[index + 1] = newValue.id;
                                setOrder([...orderF]);
                              }}
                              renderInput={(params) => (
                                <TextField {...params} label="order" />
                              )}
                            />
                          </Box>
                          {/* <MultipleSelect/> */}
                        </Box>
                      );
                    })}
                  </Box>
                  <MyTitle value="开设学院"></MyTitle>
                  <TextField
                    label="college"
                    size="small"
                    value={college}
                    sx={{ width: 130 }}
                    onChange={(e) => {
                      setCollege(e.target.value);
                    }}
                  />
                  <MyTitle value="学分"></MyTitle>
                  <TextField
                    label="credit"
                    size="small"
                    value={credit}
                    sx={{ width: 130 }}
                    onChange={(e) => {
                      setCredit(e.target.value);
                    }}
                  />
                  <MyTitle value="课程类型"></MyTitle>
                  <FormControl sx={{ mt: 0, minWidth: 80, marginBottom: 1 }}>
                    <InputLabel
                      id="demo-simple-select-autowidth-label"
                      sx={{ mt: -1 }}
                    >
                      type
                    </InputLabel>
                    <Select
                      size="small"
                      labelId="demo-simple-select-autowidth-label"
                      id="demo-simple-select-autowidth"
                      value={type}
                      onChange={(e) => {
                        setType(e.target.value);
                      }}
                      autoWidth
                      label="type"
                    >
                      {types.map((value, key) => {
                        return (
                          <MenuItem value={value.name}>{value.name}</MenuItem>
                        );
                      })}
                    </Select>
                  </FormControl>
                  <MyTitle value="课程容量"></MyTitle>
                  <TextField
                    label="capacity"
                    size="small"
                    value={capacity}
                    sx={{ width: 170 }}
                    onChange={(e) => {
                      setCapacity(e.target.value);
                    }}
                  />
                  <MyTitle value="上课地点"></MyTitle>
                  <TextField
                    label="location"
                    size="small"
                    value={location}
                    sx={{ width: 170 }}
                    onChange={(e) => {
                      setLocation(e.target.value);
                    }}
                  />
                  <MyTitle value="培养计划"></MyTitle>
                  <FormControl sx={{ mt: 0, minWidth: 80, marginBottom: 1 }}>
                    <InputLabel
                      id="demo-simple-select-autowidth-label"
                      sx={{ mt: -1 }}
                    >
                      plan
                    </InputLabel>
                    <Select
                      size="small"
                      labelId="demo-simple-select-autowidth-label"
                      id="demo-simple-select-autowidth"
                      value={pid}
                      onChange={(e) => {
                        setPid(e.target.value);
                      }}
                      autoWidth
                      label="plan"
                    >
                      {plans.map((value, key) => {
                        return (
                          <MenuItem value={value.id}>{value.name}</MenuItem>
                        );
                      })}
                    </Select>
                  </FormControl>
                  {/* 保存按钮 */}
                  <Box
                    sx={{
                      marginTop: 2,
                      marginBottom: 3,
                      marginLeft: -8,
                      display: "flex",
                      flexDirection: "column",
                      justifyContent: "center",
                      alignItems: "center",
                      width: "100%",
                    }}
                  >
                    <LoadingButton
                      titler={updbutSuccess ? "提交成功" : "提交申请"}
                      clickr={handleUpd}
                      isFetching={updLoadingT}
                      isSuccess={updbutSuccess}
                    />
                  </Box>
                </Box>
              </Box>
            </Paper>
          </Grid>
          <Grid item xs={12} md={7}>
            <Application rows={rows} getLoading={getLoading} />
          </Grid>
        </Grid>
      )}
    </LocalizationProvider>
  );
}
